#include "aisudptool.h"
#include <QUdpSocket>

AISUdpTool::AISUdpTool(QObject *parent) :
    QObject(parent),
    udpSocket(NULL)
{

}

AISUdpTool::~AISUdpTool()
{
    delete udpSocket;
}

bool AISUdpTool::StartSocket(int port, QString &multiAddress)
{
    bool bRet = false;
    do
    {
        udpSocket = new QUdpSocket(this);
        if (NULL == udpSocket)
        {
            break;
        }

        if (! udpSocket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress))
        {
            break;
        }

        if (NULL != multiAddress && ! multiAddress.isEmpty())
        {
            if (! udpSocket->joinMulticastGroup(QHostAddress(multiAddress)))
            {
                break;
            }
        }

        connect(udpSocket, SIGNAL(readyRead()),
                this, SLOT(processPendingDatagrams()));

        bRet = true;
    }
    while (false);

    return bRet;
}

bool AISUdpTool::SendData(QString &message, QString &destAddress, quint16 dstPort)
{
    bool bRet = false;
    qint64 sendedLength = udpSocket->writeDatagram(message.toUtf8(), QHostAddress(destAddress), dstPort);
    if (sendedLength > 0)
    {
        bRet = true;
    }

    return bRet;
}

void AISUdpTool::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());
        emit receivedUdpData(datagram);
    }
}
